#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
模型解释功能示例

本示例展示了如何使用MCP回归分析服务的模型解释功能，
包括算法核心思想解释、适用性分析和模型参数解释。
"""

import json
from main import (
    logistic_regression_analysis,
    polynomial_regression_analysis, 
    ridge_regression_analysis,
    generate_sample_data
)

def demonstrate_model_explanation():
    """演示模型解释功能"""
    
    print("=" * 60)
    print("MCP回归分析服务 - 模型解释功能演示")
    print("=" * 60)
    
    # 1. 逻辑回归示例
    print("\n1. 逻辑回归分析与解释")
    print("-" * 40)
    
    # 生成分类数据
    classification_data = generate_sample_data(
        data_type="classification",
        n_samples=200,
        n_features=3,
        noise=0.1
    )
    
    X_class = classification_data["X"]
    y_class = classification_data["y"]
    
    # 执行逻辑回归分析
    logistic_result = logistic_regression_analysis(
        X=X_class,
        y=y_class,
        model_id="demo_logistic_model"
    )
    
    # 展示算法解释
    print("\n算法核心思想:")
    print(logistic_result["algorithm_explanation"]["core_idea"])
    
    print("\n适用场景:")
    for scenario in logistic_result["algorithm_explanation"]["suitable_for"]:
        print(f"  • {scenario}")
    
    print("\n数据适用性分析:")
    for analysis in logistic_result["algorithm_explanation"]["data_analysis"]:
        print(f"  {analysis}")
    
    print("\n模型参数解释:")
    print(f"  决策边界: {logistic_result['model_interpretation']['decision_boundary']}")
    print(f"  截距含义: {logistic_result['model_interpretation']['intercept_meaning']}")
    
    print("\n特征系数解释:")
    for interpretation in logistic_result["model_interpretation"]["coefficient_interpretation"]:
        print(f"  {interpretation}")
    
    # 2. 多项式回归示例
    print("\n\n2. 多项式回归分析与解释")
    print("-" * 40)
    
    # 生成回归数据
    regression_data = generate_sample_data(
        data_type="regression",
        n_samples=150,
        n_features=2,
        noise=0.2
    )
    
    X_reg = regression_data["X"]
    y_reg = regression_data["y"]
    
    # 执行多项式回归分析
    poly_result = polynomial_regression_analysis(
        X=X_reg,
        y=y_reg,
        degree=3,
        model_id="demo_polynomial_model"
    )
    
    # 展示算法解释
    print("\n算法核心思想:")
    print(poly_result["algorithm_explanation"]["core_idea"])
    
    print("\n优势:")
    for advantage in poly_result["algorithm_explanation"]["advantages"]:
        print(f"  • {advantage}")
    
    print("\n局限性:")
    for limitation in poly_result["algorithm_explanation"]["limitations"]:
        print(f"  • {limitation}")
    
    print("\n模型特征分析:")
    interpretation = poly_result["model_interpretation"]
    print(f"  {interpretation['degree_analysis']}")
    print(f"  {interpretation['feature_expansion']}")
    print(f"  {interpretation['nonlinearity_capture']}")
    print(f"  过拟合风险: {interpretation['overfitting_risk']}")
    
    # 3. 岭回归示例
    print("\n\n3. 岭回归分析与解释")
    print("-" * 40)
    
    # 执行岭回归分析
    ridge_result = ridge_regression_analysis(
        X=X_reg,
        y=y_reg,
        alpha=2.0,
        model_id="demo_ridge_model"
    )
    
    # 展示算法解释
    print("\n算法核心思想:")
    print(ridge_result["algorithm_explanation"]["core_idea"])
    
    print("\n适用场景:")
    for scenario in ridge_result["algorithm_explanation"]["suitable_for"]:
        print(f"  • {scenario}")
    
    print("\n正则化效果分析:")
    interpretation = ridge_result["model_interpretation"]
    print(f"  {interpretation['regularization_effect']}")
    print(f"  {interpretation['coefficient_shrinkage']}")
    print(f"  {interpretation['multicollinearity_handling']}")
    print(f"  {interpretation['feature_retention']}")
    
    # 4. 算法选择建议
    print("\n\n4. 算法选择建议")
    print("-" * 40)
    
    print("\n基于数据特征的算法推荐:")
    print("\n• 二分类问题 → 逻辑回归")
    print("  - 输出概率值，易于解释")
    print("  - 计算效率高，适合大数据集")
    
    print("\n• 非线性关系 → 多项式回归")
    print("  - 能捕捉复杂的曲线关系")
    print("  - 适合单变量或少量变量场景")
    
    print("\n• 多重共线性 → 岭回归")
    print("  - 处理特征间相关性")
    print("  - 防止过拟合，提高泛化能力")
    
    print("\n\n=" * 60)
    print("模型解释功能演示完成")
    print("=" * 60)

def compare_algorithms():
    """比较不同算法的特点"""
    
    print("\n\n算法对比分析")
    print("=" * 60)
    
    algorithms = {
        "逻辑回归": {
            "适用问题": "二分类",
            "输出类型": "概率 + 类别",
            "线性假设": "是",
            "解释性": "高",
            "计算复杂度": "低",
            "过拟合风险": "中等"
        },
        "多项式回归": {
            "适用问题": "非线性回归",
            "输出类型": "连续值",
            "线性假设": "否",
            "解释性": "中等",
            "计算复杂度": "中等",
            "过拟合风险": "高"
        },
        "岭回归": {
            "适用问题": "多重共线性回归",
            "输出类型": "连续值",
            "线性假设": "是",
            "解释性": "中等",
            "计算复杂度": "低",
            "过拟合风险": "低"
        }
    }
    
    # 创建对比表格
    headers = ["算法", "适用问题", "输出类型", "线性假设", "解释性", "计算复杂度", "过拟合风险"]
    print(f"{'算法':<12} {'适用问题':<15} {'输出类型':<12} {'线性假设':<8} {'解释性':<8} {'计算复杂度':<10} {'过拟合风险':<10}")
    print("-" * 90)
    
    for alg_name, properties in algorithms.items():
        print(f"{alg_name:<12} {properties['适用问题']:<15} {properties['输出类型']:<12} "
              f"{properties['线性假设']:<8} {properties['解释性']:<8} {properties['计算复杂度']:<10} {properties['过拟合风险']:<10}")

if __name__ == "__main__":
    # 运行演示
    demonstrate_model_explanation()
    compare_algorithms()